/**
 * src/store/SessionStore.ts
 * 运行时会话存储模块
 * 职责：负责管理扩展运行期间的所有交互数据（聊天记录、工具结果、手动历史等）
 */

import { Message, MessageType, ToolResult, Attachment, ManualToolHistoryItem, SessionStoreConfig } from '../types/types';

export class SessionStore {

    // 存储完整的聊天消息历史
    private messages: Message[] = [];
    
    // [新增] 存储手动工具执行历史
    private manualToolHistory: ManualToolHistoryItem[] = [];
    
    // 存储当前的上下文文件
    private contextFiles: Attachment[] = [];

    // 配置
    private readonly config: Required<SessionStoreConfig> = {
        maxMessages: 100,
        maxManualHistory: 50,
        maxContextFiles: 10
    };

    constructor(config?: SessionStoreConfig) {
        if (config) {
            this.config = { ...this.config, ...config };
        }
        console.log('[SessionStore] Initialized with config:', this.config);
    }

    /**
     * 添加一条消息记录
     */
    public addMessage(message: Message): void {
        this.messages.push(message);
        this._enforceMessageLimit();
    }

    /**
     * 强制执行消息数量限制
     * @private
     */
    private _enforceMessageLimit(): void {
        if (this.messages.length > this.config.maxMessages) {
            const excess = this.messages.length - this.config.maxMessages;
            this.messages.splice(0, excess);
            console.log(`[SessionStore] Trimmed ${excess} old messages`);
        }
    }
    /**
     * 更新已存在消息的内容
     */
    public updateMessage(id: string, updates: Partial<Message>): void {
        const index = this.messages.findIndex(m => m.id === id);
        if (index !== -1) {
            this.messages[index] = { ...this.messages[index], ...updates };
        }
    }

    /**
     * 获取完整会话历史
     */
    public getHistory(): Message[] {
        return [...this.messages];
    }

    /**
     * [新增] 添加一条手动工具执行记录
     */
    public addManualHistory(item: ManualToolHistoryItem): void {
        this.manualToolHistory.push(item);
        this._enforceManualHistoryLimit();
    }

    /**
     * 强制执行手动工具历史数量限制
     * @private
     */
    private _enforceManualHistoryLimit(): void {
        if (this.manualToolHistory.length > this.config.maxManualHistory) {
            const excess = this.manualToolHistory.length - this.config.maxManualHistory;
            this.manualToolHistory.splice(0, excess);
            console.log(`[SessionStore] Trimmed ${excess} old manual history items`);
        }
    }

    /**
     * [新增] 获取所有手动工具执行记录
     */
    public getManualHistory(): ManualToolHistoryItem[] {
        return [...this.manualToolHistory];
    }

    /**
     * 设置当前上下文文件
     */
    public setContextFiles(files: Attachment[]): void {
        // 限制文件数量
        if (files.length > this.config.maxContextFiles) {
            console.warn(`[SessionStore] Limiting context files from ${files.length} to ${this.config.maxContextFiles}`);
            this.contextFiles = files.slice(0, this.config.maxContextFiles);
        } else {
            this.contextFiles = files;
        }
    }

    public getContextFiles(): Attachment[] {
        return [...this.contextFiles];
    }

    /**
     * 清空会话
     */
    public clear(): void {
        this.messages = [];
        this.manualToolHistory = []; // 同时清空工具历史
        this.contextFiles = [];
        console.log('[SessionStore] Session cleared.');
    }

    /**
     * 工厂方法：创建一个标准的消息对象
     */
    public static createMessage(
        type: MessageType, 
        content: string, 
        extras?: { 
            attachments?: Attachment[], 
            toolResult?: ToolResult,
            id?: string 
        }
    ): Message {
        return {
            id: extras?.id || `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            type,
            status: 'sent',
            content,
            timestamp: Date.now(),
            attachments: extras?.attachments,
            toolResult: extras?.toolResult
        };
    }
}